import router from '@/router/index'
import store from '@/store/index'

router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 判断用户menus不存在的时候才调用获取
      if (!store.state.user.permissions.menus) {
        await store.dispatch('permission/getPermission')
        const menus = store.state.user.permissions.menus
        const routes = await store.dispatch('permission/filterRoutes', menus)
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
        // console.log(111, routes)
        return next(to.path)
      }
      next()
    }
  } else {
    // 不登录也可以跳转的白名单页面
    const writeArr = ['/login', '/404', '/register']
    if (writeArr.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
